﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace csvviewer.adapter
{
	public class Read_line_positions_from_file
    {
        public void Process()
        {
            foreach (var position in FindLinePositions(_filename, 3))
                this.LinePosition(position);

            this.LinePosition(-1);
        }


        public event Action<long> LinePosition;
		
		
		private string _filename;
		
		public void Config(string filename)
		{
			_filename = filename;
		}


        private static IEnumerable<long> FindLinePositions(string filename, long indexOfFirstLine)
        {
            using (var f = new FileStream(filename, FileMode.Open, FileAccess.Read))
            {
                // Position on first line
                f.Seek(indexOfFirstLine, SeekOrigin.Begin);
                yield return f.Position;

                // Read all bytes...
                int b;
                while ((b = f.ReadByte()) >= 0)
                {
                    // If CR found...
                    if ((char)b == '\r')
                    {
                        //...check for following LF
                        b = f.ReadByte();
                        if (b < 0)
                            break;
                        if ((char)b == '\n')
                            // LF found, i.e. a new line is beginning after it
                            yield return f.Position;
                    }

                }
            }
        }
	}
}
